<template>
  <div class="layout-padding">
    <splitpanes>
      <pane size="10">
        <div class="layout-padding-auto layout-padding-view">
          <el-scrollbar>
            <query-tree :placeholder="$t('common.queryDeptTip')" :query="deptData.queryList" :show-expand="true"
              @node-click="handleNodeClick" :handleKeyChange="keyChangeList">
              <!-- 没有数据权限提示 -->
              <template #default="{ node, data }">
                <el-tooltip v-if="data.isLock" class="item" effect="dark" :content="$t('sysuser.noDataScopeTip')"
                  placement="right-start">
                  <span>{{ node.label }}
                    <SvgIcon name="ele-Lock" />
                  </span>
                </el-tooltip>
                <span v-if="!data.isLock">{{ node.label }}</span>
              </template>
            </query-tree>
          </el-scrollbar>
        </div>
      </pane>
      <pane size="32">
        <div class="layout-padding-auto layout-padding-view">
          <el-row>
            <div class="mb8">
              <el-row v-show="showSearch">
                <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList"
                  label-width="100px">

                  <el-form-item label="工号" prop="username">
                    <el-input v-model="state.queryForm.username" placeholder="请输入工号" clearable />
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="state.queryForm.name" placeholder="请输入姓名" clearable />
                  </el-form-item>


                  <el-form-item label="所属班次" prop="classesId">
                    <el-select class="w100" clearable placeholder="请选择所属班组" v-model="state.queryForm.classesId"
                      @change="banCiSelect(state.queryForm.classesId)">
                      <el-option :key="item.id" :label="item.classesName" :value="item.id" v-for="item in banCiLists">
                        {{ item.classesName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属班组" prop="groupId">
                    <el-select class="w100" clearable placeholder="请选择所属班组" v-model="state.queryForm.groupId">
                      <el-option :key="item.id" :label="item.groupName" :value="item.id" v-for="item in banZuLists">
                        {{ item.groupName }}
                      </el-option>
                    </el-select>
                  </el-form-item>


                  <el-form-item>

                    <el-button icon="Search" type="primary" @click="getDataList">{{
                      $t('common.queryBtn')
                    }}</el-button>
                    <el-button icon="Refresh" @click="resetQuery">{{
                      $t('common.resetBtn') }}</el-button>

                    <!-- <el-button icon="folder-add" type="primary" class="ml10" @click="selectionMoreChangDialog(userList)"
                      v-auth="'personnel_userClasses_add'">
                      批量排班
                    </el-button> -->
                  </el-form-item>
                </el-form>
              </el-row>
            </div>
          </el-row>
          <el-table style="width: 700px;" ref="multipleTableRef" :data="state.dataList" v-loading="state.loading" border
            :key='Math.random()' :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
            @row-click="rowclick" @selection-change="selectionChangHandle" @sort-change="sortChangeHandle"
            :row-style="rowStyle">
            <!-- <el-table-column type="selection" width="40" align="center" /> -->
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="username" label="工号" show-overflow-tooltip width="100" />
            <el-table-column prop="name" label="姓名" show-overflow-tooltip width="100" />
            <el-table-column prop="deptName" label="末级部门" show-overflow-tooltip width="100" />
            <el-table-column prop="classesName" label="所属班次" show-overflow-tooltip>
              <template #default="scope">
                <div>{{ scope.row.classesName == null ? '未排班' : scope.row.classesName }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="groupName" label="所属班组" show-overflow-tooltip>
              <template #default="scope">
                <div>{{ scope.row.groupName == null ? '未排班' : scope.row.groupName }}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="effectTime" label="生效时间" show-overflow-tooltip /> -->
          </el-table>
          <pagination style="width: 700px;" @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
            v-bind="state.pagination" />
        </div>
      </pane>
      <pane class="m24">
        <div class="layout-padding-auto layout-padding-view">

          <div style="display: flex;align-items: center;margin-bottom: 10px;">
            <div style="margin-right: 10px;">月份:</div>
            <el-date-picker arrow-control format="YYYY-MM-DD" value-format="YYYY-MM-DD" v-model="monthTime"
              @change="monthChange" placeholder="请选择开始时间">
            </el-date-picker>
            <el-button style="margin-left: 30px;" icon="Search" type="primary" @click="toInfo()">查看详细打卡 </el-button>
          </div>
          <div style="display: flex;align-items: center;margin-bottom: 10px;">
            <div style="background-color:#ff7777;width:20px;height:20px"></div>
            <div style="margin-left: 10px;">未出勤</div>
            <div style="background-color:#ffbb77;width:20px;height:20px;margin-left: 40px;"></div>
            <div style="margin-left: 10px;">迟到早退</div>
            <!-- <div style="background-color:#ff7777;width:30px;height:30px"></div> -->
          </div>
          <el-table :data="AMLsitInfo" border :cell-style="tableStyle.cellStyle"
            :header-cell-style="tableStyle.headerCellStyle">
            <el-table-column prop="date" label="日期" width="150">
              <template #default="scope">
                <div>{{ scope.row.date }} {{ scope.row.week }}</div>
              </template>
            </el-table-column>
            <el-table-column label="时段1">
              <el-table-column prop="signOne" label="上班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signOne != null">{{ scope.row.signOne }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
              <el-table-column prop="signTwo" label="下班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signTwo != null">{{ scope.row.signTwo }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="时段2">
              <el-table-column prop="signThree" label="上班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signThree != null">{{ scope.row.signThree }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
              <el-table-column prop="signFour" label="下班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signFour != null">{{ scope.row.signFour }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="时段3">
              <el-table-column prop="signFive" label="上班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signFive != null">{{ scope.row.signFive }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
              <el-table-column prop="signSix" label="下班" width="170">
                <template #default="scope">
                  <div v-if="scope.row.signSix != null">{{ scope.row.signSix }}</div>
                  <div v-else :style="getState(scope.row)"> </div>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="remark" label="出勤" width="260" />

          </el-table>

        </div>
      </pane>
    </splitpanes>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

  </div>
</template>

<script setup lang="ts" name="systemAttendanceManagement">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { signMonthByUsername, selectAllSignsBySection } from "/@/api/personnel/attendanceManagement";
import { formatDate } from '/@/utils/formatTime';
import { banCiList, banZuList, delObjs, deptTree, getUserList2 } from "/@/api/personnel/userClasses";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/indexUser.vue'));
// 定义查询字典
let multipleTableRef = ref('')

// 定义变量内容
const formDialogRef = ref()
//部门list
const keyChangeList = ref([])
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const userList = ref([])
const banCiLists = ref([])
const banZuLists = ref([])
const AMLsit = ref([])
const AMLsitInfo = ref([])
const startTime = ref()
const endTime = ref()
const month = ref()
const monthTime = ref()
const rowUser = ref()
const activeRowIndex = ref()
const userName = ref('')
const userNameCode = ref('')

monthTime.value = formatDate(new Date(), 'YYYY-mm-dd')
startTime.value = formatDate(new Date(), 'YYYY-mm-dd').substring(0, 8) + '01'
endTime.value = formatDate(new Date(), 'YYYY-mm-dd')
month.value = formatDate(new Date(), 'YYYY-mm-dd')
// 部门树使用的数据
const deptData = reactive({
  queryList: (name: String) => {
    return deptTree({
      deptName: name,
    });
  },
});
onMounted(() => {
  getBanCiList()
})


//实现点击表格行查询考勤
const rowclick = (row: any) => {
  // console.log('row', row);
  activeRowIndex.value = row.id
  rowUser.value = row
  userName.value = row.name
  userNameCode.value = row.username
  AMLsit.value = []
  signMonthByUsername({ username: row.username, date: monthTime.value }).then((res: any) => {
    AMLsitInfo.value = res.data
  })

}
const getState = (row) => {
  var data = row.remark == null ? '' : row.remark
  let timeflag = getTime(row.date, formatDate(new Date(), 'YYYY-mm-dd'))
  if (!timeflag) {
    return ''
  }
  if (data.includes('旷工')) {
    return 'background-color:#ff7777;width: 100%;height:30px'
  } else if (data.includes('迟到') || data.includes('早退')) {
    return 'background-color:#ffbb77;width: 100%;height:30px'
  } else if (data.includes('早退1111')) {
    return 'background-color:#ccffbb;width: 100%;height:30px'
  } else {
    return ''
  }
}
const rowStyle = (row) => {
  if (activeRowIndex.value === row.row.id) {
    return { backgroundColor: '#ffaa80' }; // 返回被点击行的样式
  }
  return {}; // 返回其他行的默认样式
}

const toInfo = () => {
  if (rowUser.value == null) {
    useMessage().error('未选择人员');
    return
  }
  formDialogRef.value.openDialog(rowUser.value)
}
const timeChange = () => {
  if (userNameCode.value == '') {
    useMessage().error('未选择人员');
    return
  }
  if (startTime.value != '' && endTime.value != '') {
    let time = getTime(startTime.value, endTime.value)
    if (time) {

      AMLsit.value = []
      selectAllSignsBySection({ username: userNameCode.value, startTime: startTime.value + ' 00:00:00', endTime: endTime.value + ' 23:59:59' }).then((res: any) => {
        // console.log('res查询考勤', res);
        AMLsit.value = res.data
      })
    } else {
      useMessage().error('开始时间不能大于结束时间');
    }

  }

}
const getTime = (time1, time2) => {
  if (time1.substring(0, 4) <= time2.substring(0, 4)) {
    if (time1.substring(5, 7) <= time2.substring(5, 7)) {
      if (time1.substring(8, 10) <= time2.substring(8, 10)) {

        return true
      } else {
        return false
      }

    } else {
      return false
    }
  } else {
    return false
  }

}
const monthChange = () => {
  if (userNameCode.value == '') {
    useMessage().error('未选择人员');
    return
  }
  AMLsitInfo.value = []
  signMonthByUsername({ username: userNameCode.value, date: monthTime.value }).then((res: any) => {
    AMLsitInfo.value = res.data
  })
}

const getBanCiList = () => {
  banCiList().then((res: any) => {
    banCiLists.value = res.data.records
    banCiLists.value.push({ id: 0, classesName: '未排班' })
  })
}

const banCiSelect = (e) => {
  state.queryForm.groupId = ''
  getBanZuList(e)
}

const getBanZuList = (e) => {
  banZuList({ classesId: e }).then((res: any) => {
    banZuLists.value = res.data.records
  })
}

// 点击树
const handleNodeClick = (e: any) => {
  AMLsit.value = []
  AMLsitInfo.value = []
  state.queryForm.pkDept = e.id;
  getDataList()
};
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  // isPage: false,
  pageList: getUserList2
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

state.queryForm.month = formatDate(new Date(), 'YYYY-mm-dd')
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}


// 导出excel
const exportExcel = () => {
  downBlobFile('/personnel/userClasses/export', Object.assign(state.queryForm, { ids: selectObjs }), 'userClasses.xlsx')
}

// 打开弹窗事件
const selectionChangDialog = (id, pkDept) => {

  // if (pkDept == null) {
  //   useMessage().error('请先选择左侧部门');
  //   return
  // }
  formDialogRef.value.openDialog(id, pkDept)
};



watch(state, (val, oldval) => {
  userName.value = ''
  AMLsit.value = []
  AMLsitInfo.value = []
  userList.value = []
  // let datas = state.dataList
  // userList.value.forEach(item => {
  //   console.log('item', item);
  //   const index = datas.findIndex((items: any) => items === item.username);
  //   if (index != -1) {
  //     multipleTableRef.value.toggleRowSelection(item)
  //   }
  //   // 
  // })

  // userList.value = state.dataList
  // for (let i = 0; i < userList.value.length; i++) {
  //   for (let index = 0; index < userList.value[i].userClassVos.length; index++) {
  //     // userList.value[i].userClassVos[index].join({ falg: false })
  //     Object.assign(userList.value[i].userClassVos[index], { falg: false })
  //     // userList.value[i].userClassVos[index].flag = false
  //   }
  // }
})

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ username }) => username);
  multiple.value = !objs.length;
  // console.log('selectObjs', selectObjs);

  if (selectObjs.value.length == 0) {
    for (const key in state.dataList) {
      let num = state.dataList[key].username
      const index = userList.value.findIndex((items: any) => items.username === num);
      // console.log('index空', index);
      if (index != -1) {
        userList.value.splice(index, 1)
      }
    }
  } else {
    for (const key in state.dataList) {
      let num = state.dataList[key].username
      const index = selectObjs.value.findIndex((items: any) => items === num);
      // console.log('index', index);
      if (index != -1) {
        const index1 = userList.value.findIndex((items: any) => items.username === num);
        // console.log('index111111111', index1);
        if (index1 == -1) {
          let data = state.dataList[key]
          userList.value.push(data)
        }
      } else {
        const index1 = userList.value.findIndex((items: any) => items.username === num);
        // console.log('判断删除', index1);

        if (index1 != -1) {
          userList.value.splice(index1, 1)
        }
      }
    }
  }
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
</script>